home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2006 June / PCpro_2006_06.ISO / files / freeware / openvip.exe / {app} / worker.py < prev    next >
Encoding:
Python Source  |  2003-06-03  |  1.6 KB  |  69 lines

  1. #
  2. # This file is part of OpenVIP (http://openvip.sourceforge.net)
  3. #
  4. # Copyright (C) 2002-2003
  5. # Michal Dvorak, Jiri Sedlar, Antonin Slavik, Vaclav Slavik, Jozef Smizansky
  6. #
  7. # This program is licensed under GNU General Public License version 2;
  8. # see file COPYING in the top level directory for details.
  9. #
  10. # $Id: worker.py,v 1.7 2003/06/03 11:00:37 vaclavslavik Exp $
  11. #
  12. # Simple worker thread interface. There are two threads in OpenVIP GUI:
  13. # the main thread (running wxPython event loop) and worked thread
  14. # (rendering using OpenVIP core).
  15. #
  16.  
  17. import threading
  18.  
  19.  
  20. stopped = False
  21. running = False
  22. queue = []
  23. cv = threading.Condition()
  24.  
  25. class Thread(threading.Thread):
  26.     def run(self):
  27.         global stopped, running
  28.         while not stopped:
  29.             cv.acquire()
  30.             while len(queue) == 0:
  31.                 if stopped: break
  32.                 cv.wait()
  33.             if stopped:
  34.                 cv.release()
  35.                 break
  36.             func,arg = queue.pop(0)
  37.             cv.release()
  38.             if arg == None: func()
  39.             else:           func(arg)
  40.         running = False
  41.  
  42. thread = None
  43.  
  44. def enqueue(func, arg=None):
  45.     """Adds a function to scheduled tasks queue."""
  46.     global thread, running
  47.     if not running:
  48.         thread = Thread()
  49.         thread.start()
  50.         running = True
  51.     if stopped:
  52.         return
  53.     cv.acquire()
  54.     queue.append((func,arg))
  55.     cv.notify()
  56.     cv.release()
  57.  
  58. def stop():
  59.     """Stops processing -- waits till the queue is empty."""
  60.     if not running: return
  61.     import time
  62.     global stopped
  63.    
  64.     cv.acquire()
  65.     stopped = True
  66.     cv.notify()
  67.     cv.release()
  68.     thread.join()
  69.